#include "combo/cximuticomb/cximuticomb_p.h"
#include "common/common.h"

#include <QLineEdit>
#include <QListWidget>
#include <controls/combo/cximuticomb.h>
MutiItem::MutiItem(const QString& display, const QVariant& data, const QVariant& tag)
	: display(display),
	  data(data),
	  tag(tag)
{
}

CXiMutiComb::CXiMutiComb(QWidget* parent)
	: QWidget(parent),
	  d_ptr(new CXiMutiCombPrivate(this))
{
	auto* common = new Common();
}
CXiMutiComb::~CXiMutiComb()
{
}

void CXiMutiComb::addItem(const QString& display, const QVariant& data, const QVariant& tag)
{
	Q_D(CXiMutiComb);
	MutiItem item;
	item.display = display;
	item.data = data;
	item.tag = tag;

	d->popup->addItem(item);
}

void CXiMutiComb::addItem(const MutiItem& item)
{
	Q_D(CXiMutiComb);
	d->popup->addItem(item);
}

void CXiMutiComb::addItems(const QList<MutiItem>& items)
{
	for (const auto& item: items)
	{
		addItem(item);
	}
}

QString CXiMutiComb::selectedDisplay() const
{
	Q_D(const CXiMutiComb);
	QStringList res;
	for (int i = 0; i < d->popup->listWidget->count(); ++i)
	{
		auto item = d->popup->listWidget->item(i);
		if (item->checkState() == Qt::Checked)
		{
			QString display = item->text();
			res.append(display);
		}
	}
	return res.join(separator());
}
QList<QVariant> CXiMutiComb::selectedData() const
{
	Q_D(const CXiMutiComb);
	QList<QVariant> res;
	for (int i = 0; i < d->popup->listWidget->count(); ++i)
	{
		auto item = d->popup->listWidget->item(i);
		if (item->checkState() == Qt::Checked)
		{
			auto var = item->data(Qt::UserRole);
			if (var.canConvert<MutiItem>())
				res.append(var.value<MutiItem>().data);
		}
	}

	return res;
}
QList<QVariant> CXiMutiComb::selectedTag() const
{
	Q_D(const CXiMutiComb);
	QList<QVariant> res;
	for (int i = 0; i < d->popup->listWidget->count(); ++i)
	{
		auto item = d->popup->listWidget->item(i);
		if (item->checkState() == Qt::Checked)
		{
			auto var = item->data(Qt::UserRole);
			if (var.canConvert<MutiItem>())
				res.append(var.value<MutiItem>().tag);
		}
	}

	return res;
}
QList<MutiItem> CXiMutiComb::selectedItems() const
{
	Q_D(const CXiMutiComb);
	QList<MutiItem> res;
	for (int i = 0; i < d->popup->listWidget->count(); ++i)
	{
		auto item = d->popup->listWidget->item(i);
		if (item->checkState() == Qt::Checked)
		{
			auto var = item->data(Qt::UserRole);
			if (var.canConvert<MutiItem>())
				res.append(var.value<MutiItem>());
		}
	}

	return res;
}
QString CXiMutiComb::separator() const
{
	Q_D(const CXiMutiComb);
	return d->separator;
}
void CXiMutiComb::setSeparator(const QString& separator)
{
	Q_D(CXiMutiComb);
	d->separator = separator;
}


void CXiMutiComb::popup()
{
	Q_D(CXiMutiComb);
	d->popup->move(mapToGlobal(QPoint(0, height())));
	d->popup->resize(this->width(), d->popup->height());
	d->popup->show();
}
void CXiMutiComb::stateChanged()
{
	Q_D(CXiMutiComb);
	d->cmbLineEdit->setText(selectedDisplay());
}

void CXiMutiComb::checkStateChanged(QListWidgetItem* row)
{
}
